package com.zzld.core.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.test.test;


/**
 * 文件上传类
 * @author 张楠
 *
 */
public class UploadFileUtil {
	 /** 实际文件所在目录 */
	private static String realFilePath = "upload";
	private static String uploadDir="";
	
	public  static List<Map<String,Object>> uploadFile(HttpServletRequest request, String suffuxDir, String allowFileType) throws IOException{
		List<Map<String,Object>> result_list=new ArrayList<Map<String,Object>>();
		boolean isNullFile=true;
		Map<String,Object> map1 = new HashMap<String,Object>();
		uploadDir=request.getSession().getServletContext().getRealPath("/")+realFilePath+File.separator;
		// 转型为MultipartHttpRequest：
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 // 遍历所有文件域，获得上传的文件  
        for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) { 
        	Map<String,Object> map = new HashMap<String,Object>();
        	 String key = it.next();
        	 MultipartFile file = multipartRequest.getFile(key);//根据key获得对象 
        	 
        	 if (file == null || file.isEmpty()){
        		 continue;  
        	 }
        	 
        	 isNullFile=false;
        	 String originalFileName="";
        	 
        	 
        	   
        	
        	 
        	 originalFileName = file.getOriginalFilename();
        	 //获取文件类型
             String fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1); 
             String fileType_result=fileterType(allowFileType,fileType);
             if(!fileType_result.equals("成功")){
            	 map.put("error", fileType_result);
            	 result_list.add(map);
            	 //return  result_list ;
             }
             String fileName = System.currentTimeMillis() +"_" + new Object().hashCode()+ new Random().nextLong() + "." + fileType; 
           
            
             saveFile(file,suffuxDir,fileName);
             map.put("fileName",fileName);
             map.put("filePath",suffuxDir+fileName);
             result_list.add(map);
            // return result_list;
        }
        if(isNullFile){
        	 map1.put("error", "文件不能为空!");
             result_list.add(map1);
             return result_list;
        }
        return result_list;
        
	}
	
	
	
	/**
	 * 文件类型过滤
	 * 
	 * @return
	 */
	private static String fileterType(String allowFileType,String fileType) {
		if (fileType.equals("") || allowFileType.indexOf(fileType.toLowerCase()) == -1) {
			return "该附件类型为"+fileType+",不允许上传,允许上传格式为"+allowFileType+"！";
		}
		return "成功";
	}
	
	/**
	 * 保存文件
	 * @param file
	 */
	private static void saveFile(MultipartFile file,String suffuxDir,String fileName) throws IOException{
		File filePath = new File(uploadDir + suffuxDir);  
        if(!filePath.exists()) {  
            filePath.mkdirs();  
        }  
        String localfileName = uploadDir + suffuxDir + fileName;  

  	    BufferedImage bi=getNewImage(file,600,800); 
  	   /* Graphics2D g = bi.createGraphics();  
  	    g.drawImage( bi, 0, 0, bi.getWidth(), bi.getHeight(), null );  
  	    g.dispose();*/  
  	    FileOutputStream fos = new FileOutputStream(localfileName.toString());  
  	    ImageIO.write(bi, "jpg", fos);  
  	   
  	    
        // 写入文件  
        File fileAbsolutePath = new File(fos.toString());  
     
        if(!fileAbsolutePath.exists()) {  
        	 
            fileAbsolutePath.createNewFile();  
        }  
        fos.close();  
        //开始上传文件  
      
        file.transferTo(fileAbsolutePath); 
       
	}
	
	private static  BufferedImage  getNewImage(MultipartFile oldImage,double width,double height) throws IOException{  
        /*srcURl 原图地址；deskURL 缩略图地址；comBase 压缩基数；scale 压缩限制(宽/高)比例*/  
          
        ByteArrayInputStream bais = new ByteArrayInputStream(oldImage.getBytes());   
        MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(bais);        
        Image src = ImageIO.read(mciis);  
        double srcHeight = src.getHeight(null);  
        double srcWidth = src.getWidth(null);  
        double deskHeight = 0;//缩略图高  
        double deskWidth  = 0;//缩略图宽  
        if (srcWidth>srcHeight) {  
              
            if (srcWidth>width) {  
                if (width/height>srcWidth/srcHeight) {  
                    deskHeight = height;  
                    deskWidth = srcWidth/(srcHeight/height);  
                }  
                else {  
                    deskHeight = width/(srcWidth/srcHeight);  
                    deskWidth = width;  
                }  
            }  
            else {  
                  
                if (srcHeight>height) {  
                    deskHeight = height;  
                    deskWidth = srcWidth/(srcHeight/height);  
                }else {  
                    deskHeight=srcHeight;  
                    deskWidth=srcWidth;  
                }  
                  
            }  
              
        }  
        else if(srcHeight>srcWidth)  
        {  
            if (srcHeight>(height)) {  
                if ((height)/width>srcHeight/srcWidth) {  
                    deskHeight = srcHeight/(srcWidth/width);  
                    deskWidth = width;  
                }else {  
                    deskHeight = height;  
                    deskWidth = (height)/(srcHeight/srcWidth);  
                }  
            }  
            else {  
                if (srcWidth>width) {  
                    deskHeight = srcHeight/(srcWidth/width);  
                    deskWidth = width;  
                }else {  
                    deskHeight=srcHeight;  
                    deskWidth=srcWidth;  
                }  
  
            }  
              
        }  
        else if (srcWidth==srcHeight) {  
              
            if (width>=(height)&&srcHeight>(height)) {  
                deskWidth=(height);  
                deskHeight=(height);  
            }  
            else if (width<=(height)&&srcWidth>width) {  
                deskWidth=width;  
                deskHeight=width;  
            }  
            else  if (width==(height)&&srcWidth<width) {  
                deskWidth=srcWidth;  
                deskHeight=srcHeight;  
            }  
            else {  
                deskHeight=srcHeight;  
                deskWidth=srcWidth;  
            }  
  
        }  
        BufferedImage tag = new BufferedImage((int)deskWidth,(int)deskHeight,  
            BufferedImage.TYPE_3BYTE_BGR);  
        tag.getGraphics().drawImage(src, 0, 0, (int)deskWidth, (int)deskHeight, null); //绘制缩小后的图  
        return tag;  
    }
	
}
